package com.argsstack;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sad
 */
public class ValueStackList {

    private final List<Args> _stacks;

    ValueStackList() {
        _stacks = new ArrayList<Args>(50);
        PushToList(new Args());
    }

    public void Clear() {
        _stacks.clear();
    }

    private Args GetTopStack() {
        return _stacks.get(ListCount() - 1);
    }

    private void PopFromList() {
        _stacks.remove(ListCount() - 1);
    }

    private int ListCount() {
        return _stacks.size();
    }

    private void PushToList(Args value) {
        _stacks.add(value);
    }

    public boolean IsNewStack() {
        return GetTopStack() == null;
    }

    public void CloneValueStack() {
        PushToList(null);
    }

    public Args GetLastFilledValueStack() {
        for (int i = ListCount() - 1; i >= 0; i--) {
            Args val = _stacks.get(i);
            if (val != null) {
                return val;
            }
        }
        return null;
    }

    public Args PeekValueStack() {
        if (IsNewStack()) {
            PopFromList();
            Args stack = GetLastFilledValueStack();
            PushToList(stack.Clone());
        }

        return GetTopStack();
    }

    public void PopButSaveLastValueStack() {
        if (IsNewStack()) {
            PopFromList();
            return;
        }
        if (ListCount() >= 2) {
            _stacks.remove(ListCount() - 2);
        } else {
            _stacks.remove(0);
        }
    }

    public void DiscardValueStack() {
        PopFromList();
    }
}
